/*
 * Copyright 2010 Electronic Business Systems Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package gr.ebs.gssdroid;

import gr.ebs.gssdroid.activities.GssGroups;
import gr.ebs.gssdroid.activities.GssLogin;
import gr.ebs.gssdroid.activities.GssMyFolders;
import gr.ebs.gssdroid.activities.GssOthers;
import gr.ebs.gssdroid.activities.GssSearch;
import gr.ebs.gssdroid.activities.GssSettings;
import gr.ebs.gssdroid.activities.GssShared;
import gr.ebs.gssdroid.activities.GssTrash;
import gr.ebs.gssdroid.http.GssHttpCommands;
import gr.ebs.gssdroid.http.GssHttpException;
import gr.ebs.gssdroid.http.SystemErrorException;
import gr.ebs.gssdroid.resource.UserResource;
import gr.ebs.gssdroid.util.UserDetails;

import java.util.ArrayList;
import java.util.Date;

import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.OnTabChangeListener;

public class GssDroid extends TabActivity implements OnTabChangeListener {
	
	public static final String BASE_REST_URL = "https://pithos.grnet.gr/pithos/rest/";
	public static final boolean useSavedData = false;
	UserResource userResource = null;
	TabHost tabHost;
	private boolean reset=false;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.main);
		setTheme(android.R.style.Theme_Light);
		GssDroidApplication app = (GssDroidApplication) getApplicationContext();
		app.setDroidActivity(this);
		if(!isOnline()){
			showErrorDialog("No Internet Connection", "GssDroid needs an internet connection.\n App will exit now.", true);
		}
		else{
			if(!app.getPreferences().hasSystemData() ){
				Intent intent = new Intent(getApplication(), GssLogin.class);
				startActivity(intent);
				return;
			}
			UserDetails details = new UserDetails(GssDroid.BASE_REST_URL, app.getPreferences().getLogin(),app.getPreferences().getToken());
			app.setUserDetails(details);
			try {
				UserResource userResource = new GssHttpCommands(details)
						.getUserResource(GssDroid.BASE_REST_URL
								+ details.getUsername());
				app.setUserResource(userResource);
			} catch (SystemErrorException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (GssHttpException e) {
				Log.d("UR","ERROR:"+e.getStatusCode()+" "+e.getMessage());
				if(e.getStatusCode()==404){
					showErrorDialog("You need to activate your account", "You have received an activation email.\nActivate your account and restart the application.", true);
				}
				if(e.getStatusCode()==403){
					loginProcess();
					finish();
					return;
				}
			}
			if(app.getUserResource()==null){
				loginProcess();
				finish();
				return;
			}
			ArrayList contentList = getContent();
			Resources res = getResources(); // Resource object to get Drawables
			tabHost = getTabHost(); // The activity TabHost
			tabHost.setBackgroundColor(Color.WHITE);
			TabHost.TabSpec spec; // Resusable TabSpec for each tab
			Intent intent; // Reusable Intent for each tab
			Intent intent2;
			// Create an Intent to launch an Activity for the tab (to be reused)
			intent2 = new Intent().setClass(this, GssMyFolders.class);
			
			if(contentList!=null)
				intent2.putExtra("content", contentList);
			else if(getIntent().getExtras()!=null && getIntent().getExtras().get("content")!=null){
				intent2.putExtra("content",(ArrayList) getIntent().getExtras().get("content"));
			}
			// Initialize a TabSpec for each tab and add it to the TabHost
			spec = tabHost
					.newTabSpec("myfolders")
					.setIndicator("My Folders",
							res.getDrawable(R.drawable.ic_tab_myfolders))
					.setContent(intent2);
	
			tabHost.addTab(spec);
	
			// add trash
			intent = new Intent().setClass(this, GssTrash.class);
			// Initialize a TabSpec for each tab and add it to the TabHost
			spec = tabHost
					.newTabSpec("trash")
					.setIndicator("Trash", res.getDrawable(R.drawable.ic_tab_trash))
					.setContent(intent);
			tabHost.addTab(spec);
	
			// add my shared
			intent = new Intent().setClass(this, GssShared.class);
			// Initialize a TabSpec for each tab and add it to the TabHost
			spec = tabHost
					.newTabSpec("myshared")
					.setIndicator("My Shared",
							res.getDrawable(R.drawable.ic_tab_shared))
					.setContent(intent);
			tabHost.addTab(spec);
	
			// add others
			intent = new Intent().setClass(this, GssOthers.class);
			// Initialize a TabSpec for each tab and add it to the TabHost
			spec = tabHost
					.newTabSpec("others")
					.setIndicator("Others",
							res.getDrawable(R.drawable.ic_tab_others))
					.setContent(intent);
			tabHost.addTab(spec);
	
			// add groups
			intent = new Intent().setClass(this, GssGroups.class);
			// Initialize a TabSpec for each tab and add it to the TabHost
			spec = tabHost
					.newTabSpec("groups")
					.setIndicator("Groups",
							res.getDrawable(R.drawable.ic_tab_groups))
					.setContent(intent);
			tabHost.addTab(spec);
			
			intent = new Intent().setClass(this, GssSearch.class);
			// Initialize a TabSpec for each tab and add it to the TabHost
			spec = tabHost
					.newTabSpec("search")
					.setIndicator("Search",
							res.getDrawable(R.drawable.ic_tab_search))
					.setContent(intent);
			tabHost.addTab(spec);
			tabHost.setOnTabChangedListener(this);
			tabHost.setCurrentTab(0);
			tabStyling();
			//setTabColors(tabHost);
			String action = getIntent().getAction();
			if (Intent.ACTION_SEND.equals(action) || "android.intent.action.SEND_MULTIPLE".equals(action)){
				
			}
		}
	}
	
	
	public void selectTab(int tab){
		reset=true;
		tabHost.setCurrentTab(tab);
	}
	
	public int getSelectedTab(){
		return tabHost.getCurrentTab();
	}
	
	protected ArrayList getContent() {
		
		Intent intent = getIntent();
			
		String action = intent.getAction();
		String type = intent.getType();
		ArrayList multi_stream=null;
		if ("android.intent.action.SEND_MULTIPLE".equals(action)){
			multi_stream = intent.getParcelableArrayListExtra((Intent.EXTRA_STREAM));
		}
		else if (Intent.ACTION_SEND.equals(action)){
			multi_stream = new ArrayList();
			multi_stream.add((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
		}
		if(multi_stream!=null)
			for (int i=0; i < multi_stream.size(); i++) {
			    Uri curStream = (Uri) multi_stream.get(i);
			    if (curStream != null && type != null) {
					String imgPath = curStream.getEncodedPath();
					
					//addMedia(imgPath, curStream);
					
				}
			}
		
		return multi_stream;

	}

	private void setTabColors(final TabHost tabHost) {
		for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
			if (i != tabHost.getCurrentTab())
				tabHost.getTabWidget().getChildAt(i)
						.setBackgroundColor(Color.WHITE);
		}
	}

	private void handleLogin() {
		Intent intent = new Intent(getApplication(), GssLogin.class);
		startActivity(intent);
		// close out this activity
		finish();
	}

	private void handleSettings() {
		Intent intent = new Intent(getApplication(), GssSettings.class);
		startActivity(intent);
		// close out this activity
		finish();
	}

	@Override
	public void onTabChanged(String tabId) {
		for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
	        tabHost.getTabWidget().getChildAt(i).setBackgroundColor(
	                Color.parseColor("#00990000"));
	        //tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 100;
	    }
	    tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab())
	            .setBackgroundColor(Color.GRAY);
	    //tabHost.getTabWidget().setDividerDrawable(R.drawable.listselector);
	    
	    tabHost.requestLayout();
	    if(reset){
	    	reset=false;
	    	((GssMyFolders)getCurrentActivity()).getTasks().getFolderTask(((GssMyFolders)getCurrentActivity())).execute(((GssDroidApplication)getApplication()).getUserResource().getFilesPath());
	    }
	    
	}

	private void tabStyling() {
		final float scale = this.getResources().getDisplayMetrics().density;
		for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
	        tabHost.getTabWidget().getChildAt(i).setBackgroundColor(
	                Color.parseColor("#00990000"));
	        final TextView tv = (TextView) getTabWidget().getChildAt(i).findViewById(android.R.id.title);        
	        tv.setTextColor(Color.BLACK);//this.getResources().getColorStateList(R.color.text_tab_indicator));
	        tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
	        ImageView iv = (ImageView)tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);
	        tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = (int) (75*scale);
	    }
	    tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab())
	            .setBackgroundColor(Color.GRAY);
	    //tabHost.getTabWidget().setDividerDrawable(R.drawable.listselector);
	    
	    tabHost.requestLayout();
	}
	
	protected void showErrorDialog(String title, String message, final boolean exit){
		AlertDialog alertDialogn = new AlertDialog.Builder(this).create();
		alertDialogn.setTitle(title);
		alertDialogn.setMessage(message);
		alertDialogn.setButton("Continue",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if(exit)
							GssDroid.this.finish();
					}
				});
		alertDialogn.setCancelable(true);
		alertDialogn.show();
	}
	
	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if(cm==null || cm.getActiveNetworkInfo()==null)
			return false;
		return cm.getActiveNetworkInfo().isConnectedOrConnecting();

	}
	
	public void loginProcess(){
		Intent intent = new Intent(getApplication(), GssLogin.class);
		ArrayList contentList = getContent();
		if(contentList!=null){
			Log.d("MNF", "PUTTING EXTRA2");
			intent.putExtra("content", contentList);
		}
		else if(getIntent().getExtras()!=null && getIntent().getExtras().get("content")!=null){
			Log.d("MNF", "PUTTING EXTRA");
			intent.putExtra("content",(ArrayList) getIntent().getExtras().get("content"));
		}
		startActivity(intent);
		// close out this activity
		finish();
	}
	
	public static String formatLocalDateTime(Date date) {
		if(date==null)
			return "";
		Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
		String datePart = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.SHORT,java.text.DateFormat.SHORT).format(convertedDate);
		return datePart;
	 }
}